import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {TableUtil} from "../../../util/table-util";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../util/response-util";
import {PageSubject} from "../../../util/page-subject";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {API, MsgConstants} from "../../../constants/constants";
import {MsgResult} from "../../../models/msg-result";
import {MonitorService} from "../site-monitor/monitor.service";
import {TreeUtil} from "../../../util/tree-util";
import {DeviceService} from "./device.service";

declare var $

@Component({
  selector: 'app-device',
  templateUrl: './device.component.html',
  styleUrls: ['./device.component.css']
})
export class DeviceComponent implements OnInit {

  table;

  deviceMonitors:Array<string>;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private treeUtil: TreeUtil,
    private dialogService: OneDialogService,
    private monitorService: MonitorService,
    private deviceService: DeviceService,
    private responseUtil:ResponseUtil,
    private pageSubject: PageSubject
  ) { }

  ngOnInit() {
    this.pushPage();
    this.initTimeConfig();
    this.initMonitorType();
    this.loadDeviceStatus();
  }


  /**
   *  生成面包屑
   */
  private pushPage() {
    let path = new Path("设备状态", null);
    this.pageSubject.pushPage("设备状态", "查询", path);
  }

  /**
   * 初始化设备类型，下拉框
   */
  private initMonitorType(){
    this.monitorService.getMonitor().subscribe(
      result => this.responseUtil.success(result ,this.processMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processMonitorResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.deviceMonitors = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   * 时间插件
   */
  private initTimeConfig() {
    $(".form_datetime").datetimepicker(
      {
        format: 'yyyy-mm-dd hh:ii',
        language: 'zh-CN',
        initialDate: new Date(),
        autoclose: true,
        todayBtn: true
      });

    $("#endTime").val(this.dateFormat(new Date(), "yyyy-MM-dd hh:mm"));
    let day1 = new Date();
    day1.setTime(day1.getTime()-60*60*1000);
    $("#startTime").val(this.dateFormat(day1, "yyyy-MM-dd hh:mm"));
  }

  /**
   * 对Date的扩展，将 Date 转化为指定格式的String
   * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
   * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
   * 例子：
   * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
   * (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
   * @param d
   * @param fmt
   * @returns {any}
   */
  private dateFormat (d,fmt) { //author: meizz
    let o = {
      "M+": d.getMonth() + 1, //月份
      "d+": d.getDate(), //日
      "h+": d.getHours(), //小时
      "m+": d.getMinutes(), //分
      "s+": d.getSeconds(), //秒
      "q+": Math.floor((d.getMonth() + 3) / 3), //季度
      "S": d.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }


  //搜索
  searchDeviceStatus(){
    this.table.bootstrapTable('refresh');
  }

  /**
   * 站点查询
   */
  loadDeviceStatus(){
    this.table = this.tableUtil.load("one_table_device",{
      columns:[
        { checkbox: true },
        { field: "_id", title:'ID',align:'left',visible:false ,switchable:false},
        { field: "deviceId", title:'设备编码',align:'left',class:'device_table',width:120},
        { field: "deviceType", title:'设备类型',align:'left',class:'device_table',formatter:this.deviceTypeFormat},
        { field: "siteName", title:'站点名称',class:'device_table',formatter:this.backgroundColor},
        { field: "sensor0Desc",title:'传感器0' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor1Desc",title:'传感器1' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor2Desc",title:'传感器2' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor3Desc",title:'传感器3' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor4Desc",title:'传感器4' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor5Desc",title:'传感器5' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor6Desc",title:'传感器6' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor7Desc",title:'传感器7' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor8Desc",title:'传感器8' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor9Desc",title:'传感器9' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor10Desc",title:'传感器10',class:'device_table',formatter:this.backgroundColor},
        { field: "sensor11Desc",title:'传感器11' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor12Desc",title:'传感器12' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor13Desc",title:'传感器13' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor14Desc",title:'传感器14' ,class:'device_table',formatter:this.backgroundColor},
        { field: "sensor15Desc",title:'传感器15' ,class:'device_table',formatter:this.backgroundColor},
        { field: "supplyVoltage",title:'供电电压' ,class:'device_table'},
        { field: "batteryVoltage",title:'电池电压' ,class:'device_table'},
        { field: "screenStatus",title:'屏幕状态' ,class:'device_table',visible:false,formatter:this.backgroundColor},
        { field: "uploadDesc",title:'上传状态' ,class:'device_table',visible:false,formatter:this.uploadBackgroundColor},
        { field: "receivetTime",title:'接收时间',visible: false}
      ],
      idField:"id",
      pagination:true,
      pageSize:15,
      pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect: true,//多选
      clickToSelect:true,//点击选中
      toolbar:".one-operation",
      url:API.getDeviceStatusCondition,
      method:'get',
      //传递附加参数
      queryParams:(params) => {
        params.deviceId = $("#device_id").val();
        params.deviceType = $("#device_Type_code").val();
        params.startTimeStr = $("#startTime").val();
        params.endTimeStr = $("#endTime").val();
        params.regionName = $("#regionName").val();
        console.log(JSON.stringify(params));
        return params;
      },
      height:700,//table高度
      showColumns:true,//显示自定义显示列按钮
      showRefresh:true,//显示刷新按钮
      minimumCountColumns:3,//最少保留显示的列数量
      showToggle:true,//显示视图切换按钮
      showPaginationSwitch:true,//显示是否分页切换按钮
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private deviceTypeFormat =(value,row,index)=>{
    if(value == '101'){
      return "油烟监测";
    }
    if(value == '102'){
      return "senko voc监测";
    }
    if(value == '256'){
      return "扬尘监测";
    }
    if(value == '257'){
      return "空气监测";
    }
    if(value == '258'){
      return "VOCs监测";
    }
    if(value == '259'){
      return "PH水质监测";
    }
    if(value == '260'){
      return "土壤监测";
    }
    if(value == '1000'){
      return "是";
    }
  }

  private backgroundColor(value,row,index){
    if('故障'!= value) return '<span>'+value+'</span>';
    return '<span style="background:red;display: block;width: 100%;padding: 3px 0;border-radius: 3px;color: #fff;">'+value+'</span>'
  }

  private uploadBackgroundColor(value,row,index){
    if('正常' != value) {
      return '<span style="background:red;display: block;width: 100%;padding: 3px 0;border-radius: 3px;color: #fff;">'+value+'</span>'
    }else{
      return '<span>'+value+'</span>';
    }
  }

}
